﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OAclient.Models;
using ServiceApplication.Service.WorkFlow;
using ServiceApplication.Service;
using System.Data;
using CommonLibrary.DataModel.Form;
using CommonLibrary.DataModel.WorkFlow;
using CommonLibrary.Common;
using System.Xml.Linq;
using Bukovics.Workflow.Hosting;
using CommonLibrary.DataModel.Basic;
using ServiceApplication.Service.Basic;
using System.Workflow.Activities;
using CommonLibrary.Wf.InterFace;
using System.Workflow.Runtime;
using System.IO;
using System.Xml;
using ServiceApplication.Dao.WorkFlow;
using System.Workflow.ComponentModel;
using System.Workflow.Runtime.Hosting;
using System.Transactions;
using ServiceApplication.Dao.Basic;
using OAclient.Common;
using OAclient.Filters;
using System.Web.UI.WebControls;
using SedionFormDesigner;
using System.Collections;
using SedionFormDesigner.Serializer.BasicStruct;

namespace OAclient.Controllers
{
    [ExceptionFilter]
    public class WorkFlowController : Controller
    {
        //
        // GET: /WorkFlow/
        WorkFlowService wfs = new WorkFlowService();
        BasicService bs = new BasicService();
        FormService fs = new FormService();
        SerializeDesigner designer = new SerializeDesigner();
        UserDao userDao = new UserDao();
        private const Int32 PageSize = 15;
        private SedinFormSerializeManager serializeManager = new SedinFormSerializeManager();

        //流程list 2-1
        public ActionResult WFList(UserModel user, String areaid)
        {
            var dt_wftype = wfs.QueryWftypeAll();
            var dt_wfall = wfs.QueryAllWfByState(1);
            DataTable dt_wf = dt_wfall.Clone();
            if (user.user.user_loginid == "admin")
            {
                ViewData["isadmin"] = "true";
                dt_wf = dt_wfall;
            }
            else
            {
                ViewData["isadmin"] = "false";
                var arr_wf = dt_wfall.AsEnumerable().Where(x => (x.Field<string>("发起人组").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Length > 0 ?
                                                                            x.Field<string>("发起人组").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).AsEnumerable().Contains(user.user.user_id.ToString()) : false));

                foreach (DataRow item in arr_wf)
                {
                    dt_wf.ImportRow(item);
                }
            }

            ViewData["dt_wftype"] = dt_wftype;
            ViewData["dt_wf"] = dt_wf;
            ViewData["user_id"] = user.user.user_id;
            ViewData["area_id"] = areaid;
            return PartialView();
        }

        //流程管理 2-1-1
        public ActionResult WFMrg(string wf_id)
        {
            WfEntity wfEntity = wfs.QueryWf(wf_id);
            var arr_fqrids = wfEntity.wf_fqrids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            ViewData["wf_name"] = wfEntity.name;
            ViewData["wf_id"] = wf_id;
            ViewData["wf_fqrids"] = wfEntity.wf_fqrids;
            //TreeNode[] tns = bs.GetWebUserNodeList();
            //foreach (TreeNode item in tns)
            //{
            //    foreach (TreeNode item2 in item.ChildNodes)
            //    {
            //        foreach (TreeNode item3 in item2.ChildNodes)
            //        {
            //            if (arr_fqrids.AsEnumerable().Contains(item3.Value))
            //            {
            //                item3.Checked = true;
            //            }
            //        }
            //        item2.ShowCheckBox = true;
            //    }
            //}
            //string s = ZTreeHelper.Serialize(tns);
            //ViewData["treeNode"] = s;

            //短信标志
            List<SelectListItem> list_wfdxbz = new List<SelectListItem>();
            list_wfdxbz.Add(new SelectListItem
            {
                Selected = 1 == wfEntity.wf_dxbz,
                Text = "是",
                Value = "1"
            });
            list_wfdxbz.Add(new SelectListItem
            {
                Selected = 0 == wfEntity.wf_dxbz,
                Text = "否",
                Value = "0"
            });
            ViewData["list_wfdxbz"] = list_wfdxbz;
            return PartialView();
        }

        //当前需要处理的任务list 2-2
        public ActionResult WFCurTaskList(UserModel user, int? page)
        {
            if (page == null) page = 1;

            var wflist = wfs.QueryAllWf();
            List<SelectListItem> wfnamelist = new List<SelectListItem>();
            foreach (DataRow row in wflist.Rows)
            {
                wfnamelist.Add(new SelectListItem
                {
                    Text = row["名称"].ToString(),
                    Value = row["名称"].ToString()
                });
            }
            ViewData["wfnamelist"] = wfnamelist;

            var wfname = Request.Form["searchwfname_wfcurtask"] ?? Request.QueryString["wfname"];
            var clrname = Request.Form["searchclrname_wfcurtask"] ?? Request.QueryString["clrname"];
            var clrid = Request.Form["searchclrid_wfcurtask"] ?? Request.QueryString["clrid"];
            var stime = Request.Form["searchstime_wfcurtask"] ?? Request.QueryString["stime"];
            var etime = Request.Form["searchetime_wfcurtask"] ?? Request.QueryString["etime"];

            ViewData["searchwfname_wfcurtask"] = wfname;
            ViewData["searchclrname_wfcurtask"] = clrname;
            ViewData["searchstime_wfcurtask"] = stime;
            ViewData["searchetime_wfcurtask"] = etime;
            //如果直接输入的名字
            if (string.IsNullOrEmpty(clrid) && !string.IsNullOrEmpty(clrname))
            {
                var clrEntity = bs.QueryUser(clrname);
                clrid = clrEntity == null ? clrid : clrEntity.user_id.ToString();
            }
            var dt_wfworking = wfs.QueryTaskByCondition(user.user.user_id.ToString(), clrid, wfname, stime, etime, "未处理");
            var pageInfo = new PagingInfo
            {
                CurrentPage = page.Value,
                ItemsPerPage = PageSize,
                TotalItems = dt_wfworking.Rows.Count
            };
            ViewData["pageInfo"] = pageInfo;
            if (dt_wfworking.Rows.Count > 0)
                dt_wfworking = dt_wfworking.AsEnumerable().Skip((page.Value - 1) * PageSize).Take(PageSize).CopyToDataTable<DataRow>();
            ViewData["dt_wfworking"] = dt_wfworking;
            ViewData["user_id"] = user.user.user_id;
            return PartialView();
        }

        //发起过的任务list  2-3
        public ActionResult WFStartList(UserModel user, int? page)
        {
            if (page == null) page = 1;

            var wflist = wfs.QueryAllWf();
            List<SelectListItem> wfnamelist = new List<SelectListItem>();
            foreach (DataRow row in wflist.Rows)
            {
                wfnamelist.Add(new SelectListItem
                {
                    Text = row["名称"].ToString(),
                    Value = row["名称"].ToString()
                });
            }
            ViewData["wfnamelist"] = wfnamelist;

            var wfname = Request.Form["searchwfname_wfstart"] ?? Request.QueryString["wfname"];
            var clrname = Request.Form["searchclrname_wfstart"] ?? Request.QueryString["clrname"];
            var clrid = Request.Form["searchclrid_wfstart"];
            var stime = Request.Form["searchstime_wfstart"] ?? Request.QueryString["stime"];
            var etime = Request.Form["searchetime_wfstart"] ?? Request.QueryString["etime"];

            ViewData["searchwfname_wfstart"] = wfname;
            ViewData["searchclrname_wfstart"] = clrname;
            ViewData["searchstime_wfstart"] = stime;
            ViewData["searchetime_wfstart"] = etime;
            //如果直接输入的名字
            if (string.IsNullOrEmpty(clrid) && !string.IsNullOrEmpty(clrname))
            {
                var clrEntity = bs.QueryUser(clrname);
                clrid = clrEntity == null ? clrid : clrEntity.user_id.ToString();
            }
            var dt_wfstart = wfs.queryStartListByConditions(user.user.user_id.ToString(), clrid, wfname, stime, etime, "'已处理','未处理','开始'");
            var pageInfo = new PagingInfo
            {
                CurrentPage = page.Value,
                ItemsPerPage = PageSize,
                TotalItems = dt_wfstart.Rows.Count
            };
            if (dt_wfstart.Rows.Count > 0)
                dt_wfstart = dt_wfstart.AsEnumerable().Skip((page.Value - 1) * PageSize).Take(PageSize).CopyToDataTable<DataRow>();

            ViewData["pageInfo"] = pageInfo;
            ViewData["dt_wfstart"] = dt_wfstart;
            return PartialView();
        }

        //处理完成的任务list
        static DataTable dt_wfworked = null;
        // 2-4
        public ActionResult WFFinishList(UserModel user, int? page)
        {
            if (page == null) page = 1;

            var wflist = wfs.QueryAllWf();
            List<SelectListItem> wfnamelist = new List<SelectListItem>();
            foreach (DataRow row in wflist.Rows)
            {
                wfnamelist.Add(new SelectListItem
                {
                    Text = row["名称"].ToString(),
                    Value = row["名称"].ToString()
                });
            }
            ViewData["wfnamelist"] = wfnamelist;

            var wfname = Request.Form["searchwfname_wffinish"] ?? Request.QueryString["wfname"];
            var clrname = Request.Form["searchclrname_wffinish"] ?? Request.QueryString["clrname"];
            var clrid = Request.Form["searchclrid_wffinish"] ?? Request.QueryString["clrid"];
            var stime = Request.Form["searchstime_wffinish"] ?? Request.QueryString["stime"];
            var etime = Request.Form["searchetime_wffinish"] ?? Request.QueryString["etime"];

            ViewData["searchwfname_wffinish"] = wfname;
            ViewData["searchclrname_wffinish"] = clrname;
            ViewData["searchstime_wffinish"] = stime;
            ViewData["searchetime_wffinish"] = etime;
            //如果直接输入的名字
            if (string.IsNullOrEmpty(clrid) && !string.IsNullOrEmpty(clrname))
            {
                var clrEntity = bs.QueryUser(clrname);
                clrid = clrEntity == null ? clrid : clrEntity.user_id.ToString();
            }
            var dt_wfworked = wfs.QueryTaskFinish(user.user.user_id.ToString(), clrid, wfname, stime, etime, "已处理");
            var pageInfo = new PagingInfo
            {
                CurrentPage = page.Value,
                ItemsPerPage = PageSize,
                TotalItems = dt_wfworked.Rows.Count
            };
            if (dt_wfworked.Rows.Count > 0)
                dt_wfworked = dt_wfworked.AsEnumerable().Skip((page.Value - 1) * PageSize).Take(PageSize).CopyToDataTable<DataRow>();

            ViewData["pageInfo"] = pageInfo;
            ViewData["dt_wfworked"] = dt_wfworked;
            return View();
        }

        //2-7
        public ActionResult WFCurDelegTaskList(UserModel user, int? page)
        {
            if (page == null) page = 1;

            var wflist = wfs.QueryAllWf();
            List<SelectListItem> wfnamelist = new List<SelectListItem>();
            foreach (DataRow row in wflist.Rows)
            {
                wfnamelist.Add(new SelectListItem
                {
                    Text = row["名称"].ToString(),
                    Value = row["名称"].ToString()
                });
            }
            ViewData["wfnamelist"] = wfnamelist;

            var wfname = Request.Form["searchwfname_wfcurdelegtasklist"] ?? Request.QueryString["wfname"];
            var stime = Request.Form["searchstime_wfcurdelegtasklist"] ?? Request.QueryString["stime"];
            var etime = Request.Form["searchetime_wfcurdelegtasklist"] ?? Request.QueryString["etime"];

            ViewData["searchwfname_wfcurdelegtasklist"] = wfname;
            ViewData["searchstime_wfcurdelegtasklist"] = stime;
            ViewData["searchetime_wfcurdelegtasklist"] = etime;

            var dt = wfs.QueryWfDelegByStrId(user.user.user_id);

            int[] wtrs = dt.AsEnumerable().Select(d => d.Field<int>("委托人编码")).ToArray();
            var dt_delegtask = wfs.QueryTaskByWtrIds(wtrs);
            var dt_arr = dt_delegtask.AsEnumerable().ToArray();
            if (!string.IsNullOrEmpty(wfname))
                dt_arr = dt_delegtask.AsEnumerable().Where(x => x["流程名称"].ToString().Contains(wfname)).ToArray();
            if (!string.IsNullOrEmpty(stime))
                dt_arr = dt_arr.AsEnumerable().Where(x => DateTime.Parse(x["开始时间"].ToString()) >= DateTime.Parse(stime + " 00:00:00")).ToArray();
            if (!string.IsNullOrEmpty(etime))
                dt_arr = dt_arr.AsEnumerable().Where(x => DateTime.Parse(x["开始时间"].ToString()) <= DateTime.Parse(etime + " 23:59:59")).ToArray();
            if (dt_arr.Length > 0)
                dt_delegtask = dt_arr.CopyToDataTable();
            else
                dt_delegtask = dt_delegtask.Clone();
            ViewData["dt_delegtask"] = dt_delegtask;
            ViewData["user_id"] = user.user.user_id;
            return View();
        }

        //完成列表查询
        public ActionResult QueryWFFinishList(UserModel user)
        {
            return View();
        }

        public ActionResult PageWFList(Int32 pageIndex)
        {
            PagingInfo pageInfo = null;

            if (dt_wfworked != null)
            {
                pageInfo = new PagingInfo
                {
                    CurrentPage = pageIndex,
                    ItemsPerPage = PageSize,
                    TotalItems = dt_wfworked.Rows.Count
                };
                if (dt_wfworked.Rows.Count > 0)
                    dt_wfworked = dt_wfworked.AsEnumerable().Skip((pageIndex - 1) * PageSize).Take(PageSize).CopyToDataTable<DataRow>();
            }

            ViewData["pageInfo"] = pageInfo;
            ViewData["dt_wfworked"] = dt_wfworked;
            return PartialView("WFFinishList");
        }

        //任务明细 2-5
        public ActionResult WFTaskDetails(string uniqueId)
        {
            DataTable dt_task = wfs.QueryTaskByuniqueId(uniqueId);
            ViewData["dt_task"] = dt_task;
            return PartialView();
        }

        //发起流程  
        public ActionResult WFStart(string wf_id, string user_id)
        {
            if (string.IsNullOrEmpty(wf_id))
            {
                return Content("不存在wf_id");
            }
            if (string.IsNullOrEmpty(user_id))
            {
                return Content("不存在user_id");
            }
            UserEntity user = bs.QueryUser(int.Parse(user_id));
            StaffEntity se = bs.QueryStaff(user.staff_id);
            DataTable dt_deptuser = bs.QueryUserByDeptId(se.dept_id.ToString());
            DataTable dt_duty = bs.QueryAllDutys();
            //获取本部门人员列表
            string[] arr_deptuser = dt_deptuser.AsEnumerable().Select(r => r["用户名称"].ToString()).ToArray();
            string[] arr_allduty = dt_duty.AsEnumerable().Select(x => x["职位名称"].ToString()).ToArray();
            DeptEntity dept = bs.QueryDept(se.dept_id);
            DutyEntity duty = bs.QueryDuty(se.duty_id);
            WfEntity wfEntity = wfs.QueryWf(wf_id);
            FormEntity formEntity = fs.QueryFormEntity(wfEntity.form_id);

            if (formEntity == null)
            {
                return Content("不存在该表单");
            }

            XElement xml = XElement.Load(Server.MapPath("~/UploadFiles/Form/" + formEntity.location));
            //WorkFlowModel wfm = new WorkFlowModel();
            //ViewData["formdefi"] = designer.DeserializeXmlToWeb(xml,
            //    new SerializeAutoData(true)
            //    {
            //        user_name = user.user_name,
            //        user_deptname = dept.dept_name,
            //        user_dutyname = duty.duty_name,
            //        user_id = user.user_id.ToString(),
            //        ComboSelfStaffList = arr_deptuser,
            //        ComboAllDutyList = arr_allduty
            //    });
            ViewData["formdefi"] = serializeManager.SerializeXmlToHtml(xml, new SedionFormDesigner.Infrastructure.SedionDesignUserInfo
            {
                UserName = user.user_name,
                UserDept = dept.dept_name,
                UserDuty = duty.duty_name,
                UserID = user.user_id.ToString(),
                Date = DateTime.Now.ToString("yyyy-MM-dd"),
                DeptID = dept.dept_id.ToString(),
                DutyID = duty.duty_id.ToString()
            });

            ViewData["form_id"] = formEntity.form_id.ToString();
            ViewData["wftemplate_id"] = wfEntity.wftemplate_id.ToString();
            ViewData["wf_id"] = wfEntity.wf_id.ToString();
            ViewData["user_id"] = user_id;
            var platelist = System.Web.HttpContext.Current.Application[MyWorkHelpr.WorkflowStaticTemplate] as Dictionary<int, StateMachineWorkflowInstance>;
            #region 获取下一步处理人类型
            WfClrxxInfo nextClr = wfs.getClrxxByFirstNext(platelist, wfEntity.wftemplate_id);

            //初始化选择树
            //ViewData["treedefi"] = ZTreeHelper.Serialize(bs.GetWebUserNodeList());

            if (nextClr != null)
            {
                if (nextClr.clzType == TaskClrType.由上一步处理人指定.ToString())
                {
                    ViewData["treevisible"] = "T";
                }
                else //特殊情况：ifelse活动的下一步处理人无法获取，所以不是 由上一步处理人指定 的情况，在createWorkflow 方法中clr传入null
                {
                    ViewData["treevisible"] = "F";
                }
            }
            #endregion
            ViewData["appendix"] = ZTreeHelper.Serialize(bs.GetStoreTree(user_id));
            return PartialView();
        }

        //审批 根据选择确定是否显示树
        public ActionResult WFProcess(UserModel user)
        {
            string str_id = Request["str_id"];//受托人编码，存在或者为null
            string uniqueid = Request["uniqueid"];
            string task_id = Request["task_id"];
            string ptask_id = Request["ptask_id"];
            ViewData["str_id"] = str_id;
            ViewData["user_id"] = user.user.user_id;
            ViewData["task_id"] = task_id;
            ViewData["ptask_id"] = ptask_id;
            var dt_spjg = wfs.QueryTaskSpjgByUniqueId(uniqueid);
            WfTaskEntity wfTaskEntity = TaskDao.Query(task_id);
            //如果存在委托审批关系，则检查当前委托关系是否还存在
            if (!string.IsNullOrEmpty(str_id))
            {
                var dt_deleg = wfs.QueryWfDelegByStrId(int.Parse(str_id));
                if (dt_deleg.AsEnumerable().Select(x => x.Field<int>("委托人编码") == wfTaskEntity.user_id).Count() == 0)
                {
                    return JavaScript("alert('委托关系已被取消');$.fn.deltab('2-2-examine');$('#menu_worktable').trigger('click');");
                }
            }
            if (wfTaskEntity.state == "已处理")
            {
                return JavaScript("alert('该任务已被处理');$.fn.deltab('2-2-examine');$('#menu_worktable').trigger('click');");
            }
            WfTaskEntity wfPTaskEntity = TaskDao.Query(wfTaskEntity.ptask_id.ToString());
            var task_clyj = wfPTaskEntity.task_clyj == String.Empty ? "无" : wfPTaskEntity.task_clyj;

            ViewData["ptask_clyj"] = task_clyj;
            FormEntity formEntity = fs.QueryFormEntityByWfinsId(wfTaskEntity.uniqueid.ToString());

            ViewData["form_id"] = formEntity.form_id;
            List<WfInsvalueEntity> wfInsvalueEntitys = wfs.QueryInsvalue(ptask_id);
            WfInsEntity wfinsEntity = wfs.queryInsEntity(uniqueid);
            WfEntity wfEntity = wfs.QueryWf(wfinsEntity.wf_id.ToString());
            if (!string.IsNullOrEmpty(wfinsEntity.ins_appendix))
            {
                //string filename = Path.GetFileNameWithoutExtension(wfinsEntity.ins_appendix);
                //ViewData["wfappendix"] = filename;
                var paths = CommonMethod.splitString(wfinsEntity.ins_appendix, ';');
                var files = String.Empty;
                foreach (var path in paths)
                {
                    var fileName = path.Substring(path.LastIndexOf("/") + 1);
                    var tmppath = HttpUtility.UrlEncode(path).ToLower();
                    var tmpfilename = HttpUtility.UrlEncode(fileName).ToLower();
                    files += "<a href='/Message/fileFromDisk?path=" + tmppath + "&fileName=" + tmpfilename + "'>" + fileName + "</a><br />";
                }
                ViewData["wfappendix"] = files;
            }
            //实例标识
            ViewData["uniqueid"] = uniqueid;
            //获取表单定义
            if (formEntity != null)
            {
                XElement xml = XElement.Load(Server.MapPath("~/UploadFiles/Form/" + formEntity.location));
                var sqlargs = wfs.getsqlargs(uniqueid);
                //xml = designer.FillInsValueToXml(xml, wfInsvalueEntitys);
                //SerializeAutoData sad = null;
                //if (dt_spjg != null)
                //{
                //    sad = new SerializeAutoData(false);
                //    for (int i = 0; i < dt_spjg.Rows.Count; i++)
                //    {
                //        sad.spyjList.Add(new AutoDataSpjg(dt_spjg.Rows[i]["审批人"].ToString(), dt_spjg.Rows[i]["部门"].ToString(), dt_spjg.Rows[i]["职位"].ToString(),
                //            dt_spjg.Rows[i]["审批意见"].ToString(), dt_spjg.Rows[i]["审批时间"].ToString(), dt_spjg.Rows[i]["审批结果"].ToString()));
                //    }
                //}
                //ViewData["formdefi"] = designer.DeserializeXmlToWeb(xml, sqlargs, true, sad);
                ViewData["formdefi"] = serializeManager.SerializeXmlToHtml(xml, conervtToFormValueEntity(wfInsvalueEntitys), dt_spjg);
            }
            //选择树定义
            //ViewData["treedefi"] = ZTreeHelper.Serialize(bs.GetWebUserNodeList());
            //获取下一步操作选项
            var StepList = new List<SelectListItem>();

            var platelist = System.Web.HttpContext.Current.Application[MyWorkHelpr.WorkflowStaticTemplate] as Dictionary<int, StateMachineWorkflowInstance>;

            DataTable dt = wfs.getNextStep(platelist[wfEntity.wftemplate_id], wfTaskEntity.taskname);
            foreach (DataRow item in dt.Rows)
            {
                StepList.Add(new SelectListItem() { Text = item["NTEXT"].ToString(), Value = item["NID"].ToString(), Selected = false });
            }
            ViewData["steplist"] = StepList;

            //已读标志
            wfs.ConfirmUnreadTask(task_id);
            return PartialView();
        }

        //新建流程  
        public ActionResult WFCreate(UserModel user)
        {
            DataTable dtType = wfs.QueryWftypeAll();
            //DataTable dtForm = fs.QueryFreeForm();
            DataTable dtForm = fs.QueryAllForm();
            DataTable dtWftemplate = wfs.QueryWfTemplate();
            List<SelectListItem> list_wftype = new List<SelectListItem>();
            for (int i = 0; i < dtType.Rows.Count; i++)
            {
                list_wftype.Add(new SelectListItem
                {
                    Selected = false,
                    Text = dtType.Rows[i]["名称"].ToString(),
                    Value = dtType.Rows[i]["编码"].ToString(),
                });
            }
            List<SelectListItem> list_form = new List<SelectListItem>();
            for (int i = 0; i < dtForm.Rows.Count; i++)
            {
                list_form.Add(new SelectListItem
                {
                    Selected = false,
                    Text = dtForm.Rows[i]["名称"].ToString(),
                    Value = dtForm.Rows[i]["编码"].ToString(),
                });
            }
            List<SelectListItem> list_wftemplate = new List<SelectListItem>();
            for (int i = 0; i < dtWftemplate.Rows.Count; i++)
            {
                list_wftemplate.Add(new SelectListItem
                {
                    Selected = false,
                    Text = dtWftemplate.Rows[i]["名称"].ToString(),
                    Value = dtWftemplate.Rows[i]["编码"].ToString(),
                });
            }
            //短信标志
            List<SelectListItem> list_wfdxbz = new List<SelectListItem>();
            list_wfdxbz.Add(new SelectListItem
            {
                Selected = false,
                Text = "是",
                Value = "1"
            });
            list_wfdxbz.Add(new SelectListItem
            {
                Selected = true,
                Text = "否",
                Value = "0"
            });

            ViewData["list_wftype"] = list_wftype;
            ViewData["list_form"] = list_form;
            ViewData["list_wftemplate"] = list_wftemplate;
            ViewData["list_wfdxbz"] = list_wfdxbz;
            ViewData["user_id"] = user.user.user_id;
            ViewData["user_name"] = user.user.user_name;
            return PartialView();
        }

        //流程模板list
        public ActionResult WFPlateList(UserModel user, Int32 page)
        {

            var dt_plate = wfs.QueryWfTemplate();
            var pageInfo = new PagingInfo
            {
                CurrentPage = page,
                ItemsPerPage = PageSize,
                TotalItems = dt_plate.Rows.Count
            };

            ViewData["pageInfo"] = pageInfo;
            if (dt_plate.Rows.Count > 0)
                dt_plate = dt_plate.AsEnumerable().Skip((page - 1) * PageSize).Take(PageSize).CopyToDataTable<DataRow>();
            ViewData["dt_plate"] = dt_plate;
            return PartialView();
        }

        public ActionResult WFTypeList()
        {
            var dt_wftype = wfs.QueryWftypeAll();
            ViewData["dt_wftype"] = dt_wftype;
            return PartialView();
        }

        public ActionResult WFTypeShow(string wftype_id)
        {
            WfTypeEntity wftypeEntity = wfs.QueryWfType(int.Parse(wftype_id));
            ViewData["wftype_id"] = wftypeEntity.wftype_id;
            ViewData["wftype_name"] = wftypeEntity.wftype_name;
            List<SelectListItem> list_wftypestatus = new List<SelectListItem>();

            list_wftypestatus.Add(new SelectListItem
            {
                Selected = wftypeEntity.wftype_status == "1",
                Text = "在用",
                Value = "1"
            });

            list_wftypestatus.Add(new SelectListItem
            {
                Selected = wftypeEntity.wftype_status != "1",
                Text = "停用",
                Value = "0",
            });
            ViewData["list_wftypestatus"] = list_wftypestatus;
            return PartialView();
        }

        public ActionResult WFTypeAdd()
        {
            return PartialView();
        }

        public ActionResult WFPlateShow(string wftemplate_id)
        {
            WfTemplateEntity dt_plate = wfs.QueryWfTemplate(int.Parse(wftemplate_id));
            ViewData["imgpath"] = dt_plate.imgpath;//ViewData["imgpath"] = "~/UploadFiles/Plate/imgProc.jpg";
            return PartialView();
        }

        //wfspqx-1
        public ActionResult WFSpqxMng()
        {
            return PartialView();
        }

        #region 委托

        //用户委托操作界面
        public ActionResult MyWFDelegMrg(UserModel user)
        {
            var dt_deleg = wfs.QueryWfDelegByWtrId(user.user.user_id);
            ViewData["dt_deleg"] = dt_deleg;
            ViewData["deleg_wtr"] = user.user.user_id;
            return PartialView();
        }

        //管理员委托管理界面
        public ActionResult WFDelegMrg(UserModel user)
        {
            var dt_deleg = wfs.QueryWfDelegValid();
            ViewData["dt_deleg"] = dt_deleg;
            return PartialView();
        }

        //委托给当前用户的流程审批列表
        public ActionResult WFCurDelegList(UserModel user)
        {
            var dt = wfs.QueryWfDelegByStrId(user.user.user_id);
            int[] wtrs = dt.AsEnumerable().Select(d => d.Field<int>("编码")).ToArray();
            var dt_delegtask = wfs.QueryTaskByWtrIds(wtrs);
            ViewData["dt_delegtask"] = dt_delegtask;
            return PartialView();
        }

        #region 委托方法
        //发起委托 管理员和员工发起都调用这个方法
        public ActionResult DoAddWfDeleg(UserModel user, string deleg_wtr, string deleg_str)
        {
            //后台验证是否已经存在有效委托
            WfDelegEntity tmp = wfs.QueryWfDelegCur(int.Parse(deleg_wtr));
            if (tmp != null)
                return Json(new ResTag(false, "已存在有效委托，请先取消"));

            if (!string.IsNullOrEmpty(deleg_wtr) && !string.IsNullOrEmpty(deleg_str))
            {
                WfDelegEntity wfDelegEntity = new WfDelegEntity()
                {
                    deleg_status = "1",
                    deleg_accept = "未处理",
                    deleg_str = int.Parse(deleg_str),
                    deleg_wtr = int.Parse(deleg_wtr),
                    deleg_stime = DateUtil.getStandardTimeBySecond(),
                    deleg_starter = user.user.user_id,
                    deleg_closer = -1,
                    deleg_etime = "",
                    deleg_rectime = "",
                    deleg_descn = "",
                };
                wfs.AddWfDeleg(wfDelegEntity);
            }
            return Json(new ResTag(true));
        }

        //取消委托
        public ActionResult DoCancelWfDeleg(UserModel user, string deleg_wtr)
        {
            WfDelegEntity wfDelegEntity = wfs.QueryWfDelegCur(int.Parse(deleg_wtr));
            if (wfDelegEntity != null)
            {
                wfDelegEntity.deleg_status = "0";
                wfDelegEntity.deleg_etime = DateUtil.getStandardTimeBySecond();
                wfDelegEntity.deleg_closer = user.user.user_id;
                wfs.UpdateWfDeleg(wfDelegEntity);
            }
            return Json(new ResTag(true));
        }



        #endregion
        #endregion

        //
        public ActionResult GetUnreadTask(UserModel user)
        {
            var dt = wfs.QueryTaskByRead(user.user.user_id.ToString(), 0);
            if (dt.Rows.Count == 0)
                return Content("NULL");
            ViewData["unread"] = dt;
            return View();
        }

        //修改task为已读
        public ActionResult ConfirmUnreadTask(String taskId)
        {
            wfs.ConfirmUnreadTask(taskId);
            return RedirectToAction("GetUnreadTask");
        }

        #region 安卓专用显示页面

        public ActionResult WFShow(int task_id)
        {
            WfTaskEntity wfTaskEntity = TaskDao.Query(task_id.ToString());
            if (null == wfTaskEntity)
            {
                return Content("不存在该流程");
            }
            WfTaskEntity wfPTaskEntity = TaskDao.Query(wfTaskEntity.ptask_id.ToString());

            ViewData["ptask_clyj"] = wfPTaskEntity == null ? "" : wfPTaskEntity.task_clyj;

            FormEntity formEntity = fs.QueryFormEntityByWfinsId(wfTaskEntity.uniqueid.ToString());
            List<WfInsvalueEntity> wfInsvalueEntitys = wfs.QueryInsvalue(wfTaskEntity.ptask_id.ToString());
            var dt_spjg = wfs.QueryTaskSpjgByTwo(wfTaskEntity.uniqueid.ToString(), wfTaskEntity.task_id.ToString());
            //实例标识
            //ViewData["uniqueid"] = wfTaskEntity.uniqueid;
            //获取表单定义
            if (formEntity != null)
            {
                XElement xml = XElement.Load(Server.MapPath("~/UploadFiles/Form/" + formEntity.location));
                var sqlargs = wfs.getsqlargs(wfTaskEntity.uniqueid.ToString());
                //xml = designer.FillInsValueToXml(xml, wfInsvalueEntitys);
                SerializeAutoData sad = null;
                if (dt_spjg != null)
                {
                    sad = new SerializeAutoData(false);
                    for (int i = 0; i < dt_spjg.Rows.Count; i++)
                    {
                        sad.spyjList.Add(new AutoDataSpjg(dt_spjg.Rows[i]["审批人"].ToString(), dt_spjg.Rows[i]["部门"].ToString(), dt_spjg.Rows[i]["职位"].ToString(),
                            dt_spjg.Rows[i]["审批意见"].ToString(), dt_spjg.Rows[i]["审批时间"].ToString(), dt_spjg.Rows[i]["审批结果"].ToString()));
                    }
                }
                var formvaluelist = conervtToFormValueEntity(wfInsvalueEntitys);
                formvaluelist.Add(new FormValueEntities() { fieldType = "spjg" });
                //ViewData["formdefi"] = designer.DeserializeXmlToWeb(xml, sqlargs, true, sad);
                ViewData["formdefi"] = serializeManager.SerializeXmlToHtml(xml, formvaluelist, dt_spjg);
            }
            //选择树定义
            //ViewData["treedefi"] = ZTreeHelper.Serialize(bs.GetWebUserNodeList());
            //获取下一步操作选项
            //var StepList = new List<SelectListItem>();
            //DataTable dt = wfs.getNextStep(wfTaskEntity.uniqueid.ToString(), (System.Web.HttpContext.Current.Application[MyWorkHelpr.WorkflowRuntimeManager] as WorkflowRuntimeManager).WorkflowRuntime);
            //foreach (DataRow item in dt.Rows)
            //{
            //    StepList.Add(new SelectListItem() { Text = item["NTEXT"].ToString(), Value = item["NID"].ToString(), Selected = false });
            //}
            //ViewData["steplist"] = StepList; 
            return View();
        }

        private List<FormValueEntities> conervtToFormValueEntity(List<WfInsvalueEntity> wfInsvalueEntitys)
        {
            var formvalueEntity = new List<FormValueEntities>();
            foreach (var item in wfInsvalueEntitys)
            {
                formvalueEntity.Add(new FormValueEntities
                {
                    fieldName = item.fieldName,
                    fieldType = item.fieldType,
                    fieldValue = item.fieldValue,
                    insvalue_id = item.insvalue_id,
                    task_id = item.task_id
                });
            }
            return formvalueEntity;
        }

        public ActionResult IP_WFStart(string wf_id, string user_id)
        {
            if (string.IsNullOrEmpty(wf_id))
            {
                return Content("不存在wf_id");
            }
            if (string.IsNullOrEmpty(user_id))
            {
                return Content("不存在user_id");
            }
            UserEntity user = bs.QueryUser(int.Parse(user_id));
            StaffEntity se = bs.QueryStaff(user.staff_id);
            DataTable dt_deptuser = bs.QueryUserByDeptId(se.dept_id.ToString());
            //获取本部门人员列表
            string[] arr_deptuser = dt_deptuser.AsEnumerable().Select(r => r["用户名称"].ToString()).ToArray();
            DeptEntity dept = bs.QueryDept(se.dept_id);
            DutyEntity duty = bs.QueryDuty(se.duty_id);
            WfEntity wfEntity = wfs.QueryWf(wf_id);
            FormEntity formEntity = fs.QueryFormEntity(wfEntity.form_id);

            if (formEntity == null)
            {
                return Content("不存在该表单");
            }

            XElement xml = XElement.Load(Server.MapPath("~/UploadFiles/Form/" + formEntity.location));
            ViewData["formdefi"] = serializeManager.SerializeXmlToHtml(xml, new SedionFormDesigner.Infrastructure.SedionDesignUserInfo
            {
                UserName = user.user_name,
                UserDept = dept.dept_name,
                UserDuty = duty.duty_name,
                UserID = user.user_id.ToString(),
                Date = DateTime.Now.ToString("yyyy-MM-dd"),
                DeptID = dept.dept_id.ToString(),
                DutyID = duty.duty_id.ToString()
            });
            //ViewData["formdefi"] = designer.DeserializeXmlToWeb(xml, new SerializeAutoData(true) { user_name = user.user_name, user_deptname = dept.dept_name, user_dutyname = duty.duty_name, user_id = user.user_id.ToString(), ComboSelfStaffList = arr_deptuser });
            ViewData["form_id"] = formEntity.form_id.ToString();
            ViewData["wftemplate_id"] = wfEntity.wftemplate_id.ToString();
            ViewData["wf_id"] = wfEntity.wf_id.ToString();
            ViewData["user_id"] = user_id;
            var platelist = System.Web.HttpContext.Current.Application[MyWorkHelpr.WorkflowStaticTemplate] as Dictionary<int, StateMachineWorkflowInstance>;
            #region 获取下一步处理人类型
            WfClrxxInfo nextClr = wfs.getClrxxByFirstNext(platelist, wfEntity.wftemplate_id);

            //初始化选择树
            //ViewData["treedefi"] = ZTreeHelper.Serialize(bs.GetWebUserNodeList());

            if (nextClr != null)
            {
                if (nextClr.clzType == TaskClrType.由上一步处理人指定.ToString())
                {
                    ViewData["treevisible"] = "T";
                }
                else //特殊情况：ifelse活动的下一步处理人无法获取，所以不是 由上一步处理人指定 的情况，在createWorkflow 方法中clr传入null
                {
                    ViewData["treevisible"] = "F";
                }
            }
            #endregion

            return PartialView();
        }

        #endregion

        #region 调用方法


        public ActionResult DoWFCreate(string user_id, string user_name, string new_name, string new_form, string new_type, string new_template, string new_bz, string new_wfdxbz)
        {
            ResTag resTag = null;
            if (string.IsNullOrEmpty(new_template)) return null;

            //判断表单和wf模板对应变量是否匹配
            WfTemplateEntity Template = wfs.QueryWfTemplate(int.Parse(new_template));
            FormEntity formEntity = fs.QueryFormEntity(int.Parse(new_form));
            if (null != formEntity.formfieldEntityList)//如果form表单中存在wf参数变量，则在rule中查询是否存在该变量名
            {
                List<string> args = new List<string>();
                foreach (var formfiledEntity in formEntity.formfieldEntityList)
                {
                    if (formfiledEntity.ifwfjudge != "")
                        args.Add(formfiledEntity.ifwfjudge);
                }
                for (int i = 0; i < args.Count; i++)
                {
                    if (!Template.wfrule.Contains(args[i]))
                    {
                        resTag = new ResTag(false, " 工作流模板中未存在输入变量 " + args[i] + " 请确认");
                        return Json(resTag);
                    }
                }
            }
            WfEntity wfEntity = new WfEntity
            {
                wftemplate_id = int.Parse(new_template),
                form_id = int.Parse(new_form),
                wftype_id = int.Parse(new_type),
                name = new_name,
                pos = 0,
                usever = 1,
                createtime = DateTime.Now.ToString(),
                lasttime = DateTime.Now.ToString(),
                creater_id = int.Parse(user_id),
                creater_name = user_name,
                lastuser_id = -1,
                lastuser_name = string.Empty,
                users = string.Empty,
                depts = string.Empty,
                status = 1,
                descn = new_bz,
                wf_fqrids = "",
                wf_dxbz = string.IsNullOrEmpty(new_wfdxbz) ? 0 : int.Parse(new_wfdxbz),
            };
            int plate_id = wfs.AddWf(wfEntity);

            //添加新的模板
            WorkflowInstance ins = null;
            WorkflowRuntimeManager workflowRuntimeManager = System.Web.HttpContext.Current.Application[MyWorkHelpr.WorkflowRuntimeManager] as WorkflowRuntimeManager;
            StateMachineWorkflowInstance stateMachineWorkflowInstance = null;
            TextReader t1 = new StringReader(Template.wfdefinition);
            TextReader t2 = new StringReader(Template.wfrule);
            XmlReader define = XmlReader.Create(t1);
            XmlReader rule = XmlReader.Create(t2);
            ins = workflowRuntimeManager.WorkflowRuntime.CreateWorkflow(define, rule, null);
            stateMachineWorkflowInstance = new
                 StateMachineWorkflowInstance(workflowRuntimeManager.WorkflowRuntime, ins.InstanceId);
            (System.Web.HttpContext.Current.Application[MyWorkHelpr.WorkflowStaticTemplate] as Dictionary<int, StateMachineWorkflowInstance>).Add(plate_id, stateMachineWorkflowInstance);
            // return RedirectToAction("SendMessage", "Message", new { url = "/WorkFlow/Index", message = "操作成功" });
            resTag = new ResTag(true);
            return Json(resTag);
            //return RedirectToAction("WFList", new { areaid = "12-1" });
        }

        public ActionResult DoWFStart()
        {
            string user_id = Request["user_id"].ToString();
            UserEntity ue = bs.QueryUser(int.Parse(user_id));
            StaffEntity se = bs.QueryStaff(ue.staff_id);
            ResTag resTag = null;
            //string wf_name = string.Empty;// Request["wf_name"];
            string ins_descn = Request["ins_descn"] ?? string.Empty;
            string form_id = Request["form_id"];
            string wftempid = Request["wftemplate_id"];
            string wf_id = Request["wf_id"];
            string sqlargs = Request["sqlargs"];

            //// 员工转正时想临时表内插入数据
            //string tmp_usr = Request["tmp_usr"];
            //bs.AddTempUser(tmp_usr);

            int[] firstClrs = null;//第一步处理人
            int[] secondClrs = null;//由界面指定的第二步处理人 只要处理方法不是 由上一步处理人指定，则该值一直保持null传入createWorkflow
            if (!string.IsNullOrEmpty(Request["selectarr"]))
            {
                string[] selectarr = Request["selectarr"].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                secondClrs = Array.ConvertAll<string, int>(selectarr, delegate(string s) { return int.Parse(s); });
            }

            List<FormFieldEntity> ffeList = new FormService().QueryFormFieldEntitys(int.Parse(form_id), "'text','textarea','checkbox','select','table'");//表单字段实体List
            List<WfInsvalueEntity> wivList = new List<WfInsvalueEntity>();//工作流实例值List
            Dictionary<string, string> dicsp = new Dictionary<string, string>();

            #region 获取页面上的工作流实例值(wivList)
            if (null != ffeList)
            {
                foreach (FormFieldEntity item in ffeList)
                {
                    wivList.Add(new WfInsvalueEntity()
                    {
                        task_id = 0,
                        fieldName = item.name,
                        fieldType = item.fieldtype,
                        fieldValue = Request.Form[item.name],
                    });
                    if (!string.IsNullOrEmpty(item.ifwfjudge))
                    {
                        dicsp.Add(item.ifwfjudge, Request.Form[item.name]);//将需要在wf中判断的字段存入dic中,传入启动的wf实例
                    }
                }
            }
            #endregion
            #region 获取附件

            string files_path = Request["wfappendix"];
            string srcfilename = string.Empty;
            string fullfilename = string.Empty;
            var paths = CommonMethod.splitString(files_path, ';');

            //if (!string.IsNullOrEmpty(file_ids))
            //{
            //    FileEntity fe = bs.FileQuery(int.Parse(file_ids));

            //    string userfile_name = Server.MapPath("~/webstore/Person/");

            //    srcfilename = Path.Combine(userfile_name, fe.user_id.ToString() + "//" + fe.file_catalog + "//" + fe.file_path);
            //var fileName = Path.GetFileName(srcfilename);//文件名
            //var fileExtend = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower();//扩展名
            //string filterExtends = ".rar,.zip,.doc,.xls,.bmp,.png,.jpeg,.gif,.txt,.jpg";
            //if (!filterExtends.Contains(fileExtend))
            //{
            //    resTag = new ResTag(false, "该文件类型不支持附件");
            //    return Json(resTag);
            //}

            //附件复制到对应文件夹 防止用户的文件删除后附件将无法下载到
            //String filepath = Server.MapPath("/");
            //filepath = Path.Combine(filepath, "UploadFiles");
            //filepath = Path.Combine(filepath, "WFAppend");
            //string newfolder = DateTime.Now.ToString("yyyyMMddHHmmss");
            //filepath = Path.Combine(filepath, newfolder);
            ////验证附件文件夹是否存在
            //if (!Directory.Exists(filepath))
            //{
            //    Directory.CreateDirectory(filepath);
            //}
            //fullfilename = Path.Combine(filepath, fe.file_name);
            //FileInfo fi = new FileInfo(srcfilename);
            //fi.CopyTo(fullfilename);
            //}

            #endregion

            var platelist = System.Web.HttpContext.Current.Application[MyWorkHelpr.WorkflowStaticTemplate] as Dictionary<int, StateMachineWorkflowInstance>;
            //下一步处理 第二个state的处理人信息
            WfClrxxInfo nextClr = wfs.getClrxxByFirstNext(platelist, int.Parse(wftempid));

            if (nextClr != null && nextClr.clzType == TaskClrType.按权限.ToString())
            {
                string[] wfspqxnames = nextClr.AsQx;
                var dt_qx = wfs.WfSpqxQuery(wfspqxnames);
                var arr_qxid = dt_qx.AsEnumerable().Select(s => s.Field<int>("编码")).ToArray();
                DataTable dt_clr = null;

                if (!nextClr.IsSelfDept)
                    dt_clr = bs.QueryUserBySpqx(arr_qxid);
                else
                    dt_clr = bs.QueryUserBySpqxDept(arr_qxid, se.dept_id);

                //按职务的类型下如果有多人，则多人抢占式发起
                if (dt_clr != null && dt_clr.Rows.Count > 0)
                {
                    secondClrs = dt_clr.AsEnumerable().Select(d => d.Field<int>("用户编码")).ToArray();
                }
                else
                {
                    resTag = new ResTag(false, "下一步处理人不存在，请确认");
                    return Json(resTag);
                }
            }
            else if (nextClr != null && nextClr.clzType == TaskClrType.发起人.ToString())
            {
                secondClrs = new int[] { ue.user_id };
            }
            //wfname 保存流程名字
            WfEntity wfEntity = wfs.QueryWf(wf_id);

            WorkflowRuntimeManager manager = System.Web.HttpContext.Current.Application[MyWorkHelpr.WorkflowRuntimeManager] as WorkflowRuntimeManager;
            manager.WorkflowRuntime.StartRuntime();
            {
                StartParameter sp = new StartParameter()
                {
                    createrInfo = ue,
                    insValue = dicsp,
                    wfName = wfEntity.name,//界面上获取,默认demo
                    firstClr = firstClrs,
                    secondClr = secondClrs,
                    firstCllx = nextClr.clzType, //处理类型
                    sqlargs = sqlargs,
                    clrid = null,
                    ins_descn = ins_descn,
                    wfappendix = files_path //FileHelper.GetRelName(fullfilename, FileHelper.RelFileTag.wfappendfiletag)//保存为相对路径
                };

                resTag = wfs.DoWfStart(
                   manager, int.Parse(wftempid), int.Parse(wf_id), sp, wivList, platelist);
                return Json(resTag);
                //if (resTag.res)
                //    //return RedirectToAction("WFStartList", new { page = 1 });
                //    return Content("<javascript><br/><br/>操作成功<javascript>");
                //else
                //    return Content(resTag.msg);
            }

            //return RedirectToAction("SendMessage", "Message", new { url = "/WorkFlow/Index", message = "操作成功" });
        }

        public ActionResult DoWFProcess()
        {
            //string user_id = Request["user_id"];
            //var ue = bs.QueryUser(int.Parse(user_id));
            string str_id = Request["str_id"];
            string task_id = Request["task_id"];
            WfTaskEntity wftaskEntity = wfs.QueryTask(task_id);
            //如果存在委托审批关系，则检查当前委托关系是否还存在
            if (!string.IsNullOrEmpty(str_id))
            {
                var dt = wfs.QueryWfDelegByStrId(int.Parse(str_id));
                if (dt.AsEnumerable().Select(x => x.Field<int>("委托人编码") == wftaskEntity.user_id).Count() == 0)
                {
                    return JavaScript("alert('委托关系已被取消')");
                }
            }
            string ptask_id = Request["ptask_id"];
            string task_clyj = Request["task_clyj"];
            string form_id = Request["form_id"];
            int[] clrs = null;//只要 处理方法不是 由上一步处理人指定，则该值一直保持null传入createWorkflow
            if (!string.IsNullOrEmpty(Request["selectarr"]))
            {
                string[] selectarr = Request["selectarr"].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                clrs = Array.ConvertAll<string, int>(selectarr, delegate(string d) { return int.Parse(d); });
            }
            string guid = Request["txtGUID"];
            string taskname = Request["steplist"];
            string task_des = Request["task_des"];

            Guid instanceId = new Guid(guid);


            if (wftaskEntity.state == "已处理")
            {
                return Json(new ResTag(false, "该待办已审批"));
            }
            UserEntity fqrEntity = bs.QueryUser(wftaskEntity.fqrcode);
            #region 数据获取: 表单值wivList
            List<WfInsvalueEntity> wivList = wfs.QueryInsvalue(ptask_id);
            wivList.ForEach(x => x.task_id = int.Parse(task_id));

            //根据 当前不支持修改表单，所以form的值直接取上次审批的值
            //List<FormFieldEntity> ffeList = new FormService().QueryFormFieldEntitys(int.Parse(form_id), "'text','textarea','checkbox','select'");
            //List<WfInsvalueEntity> wivList = new List<WfInsvalueEntity>();
            //if (null != ffeList)
            //{
            //    foreach (FormFieldEntity item in ffeList)
            //    {
            //        wivList.Add(new WfInsvalueEntity()
            //        {
            //            task_id = int.Parse(task_id),
            //            fieldName = item.name,
            //            fieldType = item.fieldtype,
            //            fieldValue = Request.Form[item.name]
            //        });
            //    }
            //}
            #endregion
            var platelist = System.Web.HttpContext.Current.Application[MyWorkHelpr.WorkflowStaticTemplate] as Dictionary<int, StateMachineWorkflowInstance>;
            WorkflowRuntimeManager manager = (System.Web.HttpContext.Current.Application[MyWorkHelpr.WorkflowRuntimeManager] as WorkflowRuntimeManager);
            {
                var resTag = wfs.DoWfProcess2(manager, instanceId, fqrEntity, task_id, ptask_id, taskname, task_des, task_clyj, wivList, clrs, platelist, "");
                return Json(resTag);
                //if (resTag.res)
                //    //return RedirectToAction("WFCurTaskList");

                //    return Content("<javascript>alert('操作成功');proRes(true)<javascript>");
                //else
                //    return Content("<javascript>alert('"+ resTag.msg + "')<javascript>");
            }
        }

        public ActionResult DoWFCancel(string task_id)
        {
            WorkflowRuntimeManager manager = (System.Web.HttpContext.Current.Application[MyWorkHelpr.WorkflowRuntimeManager] as WorkflowRuntimeManager);
            {
                var res = wfs.DoWfCancel(task_id, manager);
                return Json(res, JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult DoWFTypeAdd(string wftype_name)
        {
            WfTypeEntity wftypeEntity = new WfTypeEntity()
            {
                wftype_name = wftype_name,
                wftype_status = "1",
            };

            wfs.AddWfType(wftypeEntity);
            return RedirectToAction("WFTypeList");
        }

        public ActionResult DoWFTypeUpdate(string wftype_id, string wftype_name, string wftype_status)
        {
            WfTypeEntity wftypeEntity = wfs.QueryWfType(int.Parse(wftype_id));
            wftypeEntity.wftype_name = wftype_name;
            wftypeEntity.wftype_status = wftype_status;
            wfs.UpdateWfType(wftypeEntity);

            return RedirectToAction("WFTypeList");
        }


        //当处理界面选择不同的处理方式时，根据处理名称查找下一步的处理方式
        //taskname 就是 eventdriven.name
        [HttpPost]
        public JsonResult InityTree(string eventDrivenName, string eventDrivenDesc, string guid, string task_id)
        {
            ResTag resTag = null;

            //如果为空，则说明是选择了默认的那条，不用操作生成树
            //备注：设置默认条目是为了让客户初次进行选择操作来触发当前方法，
            //           初始化的时候进行是否生成树判断比较麻烦，所以采取了让客户进行选择操作的方法
            if (string.IsNullOrEmpty(eventDrivenName))
            {
                resTag = new ResTag(false, "请选择处理结果", "[]");
                return Json(resTag);
            }
            //var wfrManger = System.Web.HttpContext.Current.Application[MyWorkHelpr.WorkflowRuntimeManager] as WorkflowRuntimeManager;
            Guid instanceId = new Guid(guid);

            //StateMachineWorkflowInstance stateInstance = new StateMachineWorkflowInstance(wfrManger.WorkflowRuntime, instanceId);
            //EventDrivenActivity edact = (EventDrivenActivity)stateInstance.CurrentState.Activities[taskname];
            var platelist = System.Web.HttpContext.Current.Application[MyWorkHelpr.WorkflowStaticTemplate] as Dictionary<int, StateMachineWorkflowInstance>;
            WfEntity wfEntity = wfs.QueryWfByuniqueid(guid);
            WfTaskEntity wftaskEntity = wfs.QueryTask(task_id);

            var wfinsEntity = wfs.queryInsEntity(guid);
            var fqrEntity = bs.QueryUser(wfinsEntity.user_id);
            var se = bs.QueryStaff(fqrEntity.staff_id);
            var task_refuse = wfs.taskRefuse(platelist, wfEntity.wftemplate_id, wftaskEntity.taskname, eventDrivenDesc);
            if (task_refuse)
            {
                resTag = new ResTag(true, "", "[]");
                return Json(resTag);
            }
            WfClrxxInfo clrxx = wfs.getNextClrxxByTaskName(platelist, wfEntity.wftemplate_id, wftaskEntity.taskname, eventDrivenDesc);

            if (clrxx != null && clrxx.clzType == TaskClrType.按权限.ToString())
            {
                string[] wfspqxnames = clrxx.AsQx;
                var dt_qx = wfs.WfSpqxQuery(wfspqxnames);
                var arr_qxid = dt_qx.AsEnumerable().Select(s => s.Field<int>("编码")).ToArray();
                DataTable dt_clr = null;

                if (!clrxx.IsSelfDept)
                    dt_clr = bs.QueryUserBySpqx(arr_qxid);
                else
                    dt_clr = bs.QueryUserBySpqxDept(arr_qxid, se.dept_id);

                //按职务的类型下如果有多人，则多人抢占式发起
                if (dt_clr != null && dt_clr.Rows.Count > 0)
                {
                    //clrs = dt_clr.AsEnumerable().Select(d => d.Field<int>("id")).ToArray();
                    resTag = new ResTag(true, "", "[]");
                }
                else//如果按权限处理人不存在，则转为选择树
                {
                    //return new ResTag(false, "下一步处理人不存在，请确认");
                    resTag = new ResTag(false, "下一步处理人不存在，请自行选择", ZTreeHelper.Serialize(bs.GetWebUserNodeList()));
                }
            }
            else if (clrxx != null && clrxx.clzType == TaskClrType.由上一步处理人指定.ToString())
            {
                resTag = new ResTag(true, "", ZTreeHelper.Serialize(bs.GetWebUserNodeList()));
            }
            else
            {
                resTag = new ResTag(true, "", "[]");
            }

            return Json(resTag);
        }

        public ActionResult DoGetAppendix(string uniqueid)
        {
            string appendfile_name = Server.MapPath("~/UploadFiles/WFAppend/");
            WfInsEntity wfinsEntity = wfs.queryInsEntity(uniqueid);
            string fullfilename = Path.Combine(appendfile_name, wfinsEntity.ins_appendix);
            string filename = Path.GetFileName(fullfilename);

            if (System.IO.File.Exists(fullfilename))
                return File(new FileStream(fullfilename, FileMode.Open), "application/octet-stream", filename);
            else
                return Content("文件不存在");
        }

        public ActionResult DoSaveWfFqqx(string wf_id, string scter_ids, string wf_dxbz)
        {
            if (string.IsNullOrEmpty(wf_id))
            {
                return Json(new ResTag(false, "操作失败"));
            }
            if (string.IsNullOrEmpty(scter_ids))
            {
                return Json(new ResTag(false, "至少选择一个人员"));
            }
            WfEntity wfEntity = wfs.QueryWf(wf_id);
            wfEntity.wf_fqrids = scter_ids;
            wfEntity.wf_dxbz = int.Parse(wf_dxbz);
            wfs.UpdateWf(wfEntity);
            return Json(new ResTag(true));
        }

        public ActionResult DoGetTaskFlowChart(string uniqueId)
        {
            DataTable dt_task = wfs.QueryTaskByuniqueId(uniqueId);
            dt_task.DefaultView.Sort = "任务编码";
            dt_task = dt_task.DefaultView.ToTable();
            int i = 1;
            var list = from q in dt_task.AsEnumerable()
                       where q["父级编码"].ToString() != "-1"
                       select new
                       {
                           id = q["任务编码"].ToString(),
                           title = (i++).ToString() + "、" + q["任务名称"].ToString(),
                           summary = " 处理人:" + q["处理人"].ToString() + "<br/>"
                                         + " 处理结果:" + q["处理结果"].ToString() + "<br/>"
                               //+ " <a onclick=openWin(&apos;/WorkFlow/WFShow?task_id=" + q["任务编码"].ToString() + "&apos;,100,100,800,1000) >查看</a>",
                                         + " <a href='/WorkFlow/WFShow?task_id=" + q["任务编码"].ToString() + "'  target='_blank'>查看</a>",
                           content = " 处理人:" + q["处理人"].ToString() + "<br/>"
                                      + "任务状态:" + q["任务状态"].ToString() + "<br/>"
                                      + " 处理结果:" + q["处理结果"].ToString() + "<br/>"
                                      + " 开始时间:" + q["开始时间"].ToString() + "<br/>"
                                      + " 完成时间:" + q["完成时间"].ToString() + "<br/>",
                           type = "p",
                           condit = new Object[]
                           {
                              new
                              { 
                                pid = q["父级编码"].ToString(),
                                content = ""
                              }
                           }
                       };


            var data = new { procedures = list };
            ViewData["dt_task"] = dt_task;
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        public ActionResult DoGetWFChart(int wftemplate_id)
        {
            //WfEntity we = wfs.QueryWf(wf_id);
            var platelist = System.Web.HttpContext.Current.Application[MyWorkHelpr.WorkflowStaticTemplate] as Dictionary<int, StateMachineWorkflowInstance>;
            StateMachineWorkflowInstance wfInstance = platelist[wftemplate_id];
            DataTable dt = wfs.getWFPlateChart(wfInstance);
            var distinctStateList = (from q in dt.AsEnumerable()
                                     select new { name = q["状态名称"], clrs = q["处理人"], cllx = q["处理类型"] }).Distinct();

            int i = 1;
            var list = from p in distinctStateList
                       select new
                       {
                           id = p.name,
                           title = (i++).ToString() + "、" + p.name,
                           summary = "处理类型:" + p.cllx + "<br/>"
                                         + "处理人:" + p.clrs + "<br/>",
                           type = "c",
                           condit = from q in dt.AsEnumerable()
                                    where q["状态名称"] == p.name
                                    select new
                                    {
                                        cid = q["下一步状态名"].ToString(),
                                        content = q["事件描述"]
                                    }
                       };

            var data = new { procedures = list };
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        //流程权限对应的用户树
        public ActionResult DoGetUserTreeByWfId(string wf_id)
        {
            WfEntity wfEntity = wfs.QueryWf(wf_id);
            var arr_fqrids = wfEntity.wf_fqrids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            var dt_dept = bs.QueryAllDepts();
            var duty_ids = dt_dept.AsEnumerable().Select(x => x["部门编码"]).ToArray();
            var dt_user = bs.QueryAllUsers();
            dt_user = dt_user.Select("在职标志 = '在职' ").CopyToDataTable();
            var childtree = from q in duty_ids
                            select new
                            {
                                id = q,
                                name = dt_dept.AsEnumerable().Where(x => x["部门编码"].ToString() == q.ToString()).ToArray().First()["部门名称"].ToString(),
                                nocheck = false,
                                open = false,
                                tag = "部门",
                                children = from p in dt_user.AsEnumerable()
                                           where p["部门编码"].ToString() == q.ToString()
                                           select new
                                           {
                                               id = p["用户编码"],
                                               name = p["用户名称"],
                                               nocheck = false,
                                               @checked = arr_fqrids.Contains(p["用户编码"].ToString()),
                                               open = false,
                                               tag = "用户"
                                           }
                            };
            var objtree = new { id = -1, name = "公司部门", nocheck = false, open = true, children = childtree };
            return Json(objtree, JsonRequestBehavior.AllowGet);
        }

        #region 权限管理

        //查询对应的审批权限  
        public ActionResult DoGetWFSpaxTreeBySpqxId(string spqx_id)
        {
            if (string.IsNullOrEmpty(spqx_id))
            {
                return Content(string.Empty);
            }
            var dt = wfs.SpqxdybQuery(spqx_id, null);
            var arr_user_ids = dt.AsEnumerable().Select(x => x["用户编码"].ToString()).ToArray();

            var dt_dept = bs.QueryAllDepts();
            var dept_ids = dt_dept.AsEnumerable().Select(x => x["部门编码"]).ToArray();
            var dt_user = bs.QueryAllUsers();
            dt_user = dt_user.Select("在职标志 = '在职' ").CopyToDataTable();
            var childtree = from q in dept_ids
                            select new
                            {
                                id = q,
                                name = dt_dept.AsEnumerable().Where(x => x["部门编码"].ToString() == q.ToString()).ToArray().First()["部门名称"].ToString(),
                                nocheck = false,
                                open = false,
                                tag = "部门",
                                children = from p in dt_user.AsEnumerable()
                                           where p["部门编码"].ToString() == q.ToString()
                                           select new
                                           {
                                               id = p["用户编码"],
                                               name = p["用户名称"],
                                               nocheck = false,
                                               @checked = arr_user_ids.Contains(p["用户编码"].ToString()),
                                               open = false,
                                               tag = "用户"
                                           }
                            };
            var objtree = new { id = -1, name = "公司部门", nocheck = false, open = true, children = childtree };
            return Json(objtree);
        }

        public ActionResult DoGetWFSpaxTreeByUserId(string user_id)
        {
            if (string.IsNullOrEmpty(user_id))
            {
                return Content(string.Empty);
            }
            var dt = wfs.SpqxdybQuery(null, user_id);
            var childtree = from q in dt.AsEnumerable()
                            select new
                            {
                                id = q["权限编码"],
                                name = q["权限名称"],
                                nocheck = true,
                                open = false,
                                tag = "",
                            };
            return Json(childtree, JsonRequestBehavior.AllowGet);
        }

        public ActionResult DoSaveWfSpqxBySpqxId(string spqx_id, string user_ids)
        {
            if (string.IsNullOrEmpty(spqx_id) || string.IsNullOrEmpty(user_ids))
            {
                return Json(new ResTag(false), JsonRequestBehavior.AllowGet);
            }
            var arr_user_id = user_ids.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

            wfs.SpqxdybUpdateBySpqxId(int.Parse(spqx_id), arr_user_id);

            return Json(new ResTag(true), JsonRequestBehavior.AllowGet);
        }
        public ActionResult DoSaveWfSpqxByUserId(string user_id, string spqx_ids)
        {
            if (string.IsNullOrEmpty(user_id) || string.IsNullOrEmpty(spqx_ids))
            {
                return Json(new ResTag(false), JsonRequestBehavior.AllowGet);
            }
            var arr_spqx_id = spqx_ids.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);


            wfs.SpqxdybUpdateByUserId(arr_spqx_id, int.Parse(user_id));

            return Json(new ResTag(true), JsonRequestBehavior.AllowGet);
        }
        #endregion
        #endregion
    }
}